﻿using System;
using System.Collections.ObjectModel;
using SoccerLiveScores.Models;
using System.Net;
using System.Linq;
using System.Xml.Linq;
using SoccerLiveScores.Exceptions;
using SoccerLiveScores.Extensions;
using System.Collections.Generic;

namespace SoccerLiveScores.ViewModels
{
    public class ListPageViewModel : PageViewModel
    {
        private ObservableCollection<ScoreModel> _contextCollection = new ObservableCollection<ScoreModel>();

        public string FilterText
        {
            get;
            set;
        }

        public bool IsDataLoaded
        {
            get;
            private set;
        }

        public bool HasError
        {
            get { return Error != null; }
        }

        public ScoreException Error
        {
            get;
            set;
        }

        public void LoadData()
        {
            if (string.IsNullOrEmpty(Url))
            {
                LoadData(Competitions.DefaultUrl);
            }
            else
            {
                LoadData(Url);
            }
        }

        public void LoadData(string url)
        {
            ContextCollection.Clear();
            var webClient = new WebClient();
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            webClient.DownloadStringAsync(new Uri(url));
        }

        private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Error = new ScoreException("Unable to retrieve data.", e.Error);
            }
            XElement rss = XElement.Parse(e.Result);

            var items = from tussenstand in rss.Descendants("item")
                        select new ScoreModel
                        {
                            Title = tussenstand.Element("title").Value,
                            Description = tussenstand.Element("description").Value,
                            PubDate = tussenstand.Element("pubDate").Value
                        };

            UpdateCollection(items);
            UpdateFilter(FilterText);

            IsDataLoaded = true;
        }

        public void UpdateFilter(string filter)
        {
            FilterText = filter;
            IEnumerable<ScoreModel> filteredItems = null;
            if (!string.IsNullOrEmpty(FilterText))
            {
                filteredItems = ContextCollection.Where(i => i.Title.ToLower().Contains(FilterText.ToLower()));
                UpdateCollection(filteredItems);
            }            
        }

        private void UpdateCollection(IEnumerable<ScoreModel> items)
        {
            var newCollection = new ObservableCollection<ScoreModel>();
            foreach (var item in items)
            {
                // Filter for "Claim your 25£ free bet att William Hill. Use promo code F25 when opening an account!"
                if (!item.Title.Contains("Claim your"))
                {
                    item.StripHTML();
                    newCollection.Add(item);
                }
            }
            ContextCollection = newCollection;
        }

        public ObservableCollection<ScoreModel> ContextCollection
        {
            get { return _contextCollection; }
            set
            {
                if (_contextCollection != value)
                {
                    _contextCollection = value;
                    OnPropertyChanged("ContextCollection");
                }
            }
        }
    }
}
